﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ww.wwf.wwfbll;
using System.IO;

namespace ww.form.wwf
{
    public partial class PersonAddForm : Form
    {
        DeptBll bllDept = new DeptBll();
        PersonBLL bll = new PersonBLL();
        DataTable dtPerson = new DataTable();      
        string strDeptID = "";//部门ID
        string strPersonID = "";//人员ID
        int intEdit = 0;//0为新增，1为修改
        public PersonAddForm(string fdept_id, string fperson_id,int fedit)
        {
            InitializeComponent();            
            strDeptID = fdept_id;
            strPersonID = fperson_id;
            intEdit = fedit;
        }

        private void PersonAddForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.fdept_idTextBox.Text = bllDept.BllDeptNameByID(strDeptID);                

                if (intEdit == 0)
                {
                    dtPerson = this.bll.BllDTByID("-2");
                    wwf_personBindingSource.DataSource = dtPerson;
                    this.fpassTextBox.Enabled = true;
                    this.fperson_idTextBox.Enabled = true;
                    AddNewRow();
                }
                else if (intEdit == 1)
                {
                    //修改记录
                    dtPerson = this.bll.BllDTByID(strPersonID);
                    wwf_personBindingSource.DataSource = dtPerson;


                    this.fpassTextBox.Enabled = false;
                    this.fperson_idTextBox.Enabled = false;
                }
            
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }

        private void SaveUpdate()
        {
            try
            {               
                if (this.fnameTextBox.Text == "" || this.fnameTextBox.Text == null)
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowWarning("姓名不能为空，请填写后重试！");
                    return;
                }                
                else
                {                   
                    dtPerson.Rows[0]["fname"] = this.fnameTextBox.Text;
                   // dtPerson.Rows[0]["fpass"] = ww.wwf.com.Security.StrToEncrypt("MD5", this.fpassTextBox.Text);
                    dtPerson.Rows[0]["fname_e"] = this.fname_eTextBox.Text;
                    dtPerson.Rows[0]["forder_by"] = this.forder_byTextBox.Text;
                    dtPerson.Rows[0]["ftype"] = this.ftypeTextBox.Text;                    
                    if (fuse_flagCheckBox.Checked)
                        dtPerson.Rows[0]["fuse_flag"] = "1";
                    else
                        dtPerson.Rows[0]["fuse_flag"] = "0";
                    dtPerson.Rows[0]["fremark"] = this.fremarkTextBox.Text;
                    dtPerson.Rows[0]["fshow_name"] = "(" + dtPerson.Rows[0]["fperson_id"].ToString() + ")" + this.fnameTextBox.Text;
                    if (str_picpath != "")
                        dtPerson.Rows[0]["fpreson_img"] = File2Bytes(str_picpath);

                    this.Validate();
                    //MessageBox.Show(dtPerson.Rows[0]["fpreson_img"].ToString());
                    this.wwf_personBindingSource.EndEdit();
                    if (this.bll.BllUpdate(dtPerson) > 0)
                    {
                        ww.wwf.wwfbll.WWMessage.MessageShowInformation("用户修改成功！");
                        this.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }
        private void SaveAdd()
        {
            try
            {
                if (this.fperson_idTextBox.Text == "" || this.fperson_idTextBox.Text == null)
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowWarning("登录名不能为空，请填写后重试！");
                    return;
                }
                if (this.fnameTextBox.Text == "" || this.fnameTextBox.Text == null)
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowWarning("姓名不能为空，请填写后重试！");
                    return;
                }
                if (this.bll.BllPersonExists(this.fperson_idTextBox.Text))
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowWarning("登录名为" + this.fperson_idTextBox.Text + "的用户已经存在！");
                    return;
                }
                else
                {

                    dtPerson.Rows[0]["fperson_id"] = this.fperson_idTextBox.Text;
                    dtPerson.Rows[0]["fdept_id"] = this.strDeptID;
                    dtPerson.Rows[0]["fname"] = this.fnameTextBox.Text;
                    dtPerson.Rows[0]["fpass"] = ww.wwf.com.Security.StrToEncrypt("MD5", this.fpassTextBox.Text);
                    dtPerson.Rows[0]["fname_e"] = this.fname_eTextBox.Text;
                    dtPerson.Rows[0]["forder_by"] = this.forder_byTextBox.Text;
                    dtPerson.Rows[0]["ftype"] = this.ftypeTextBox.Text;


                    dtPerson.Rows[0]["fhelp_code"] = ww.wwf.com.Spell.MakeSpellCodeFirstLetterOnly(fnameTextBox.Text);
                    //sqlHelp = ww.wwf.com.Spell.MakeSpellCodeFirstLetterOnly(DataGridViewObject.Rows[i].Cells["fname"].Value.ToString().Trim());

                    if (fuse_flagCheckBox.Checked)
                        dtPerson.Rows[0]["fuse_flag"] = "1";
                    else
                        dtPerson.Rows[0]["fuse_flag"] = "0";
                    dtPerson.Rows[0]["fremark"] = this.fremarkTextBox.Text;
                    dtPerson.Rows[0]["fshow_name"] = "(" + this.fperson_idTextBox.Text + ")" + this.fnameTextBox.Text;

                    if (str_picpath != "")
                        dtPerson.Rows[0]["fpreson_img"] = File2Bytes(str_picpath);

                    this.Validate();
                    this.wwf_personBindingSource.EndEdit();
                    if (this.bll.BllAdd(dtPerson) > 0)
                    {
                        ww.wwf.wwfbll.WWMessage.MessageShowInformation("用户增加成功！");
                        AddNewRow();
                    }
                }
            }
            catch(Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError("请新增功能后再保存！"+ex.Message.ToString());
            }
        }
        private void AddNewRow()
        {
            if (dtPerson != null)
                dtPerson.Clear();
            DataRow dr = null;
            dr = dtPerson.NewRow();
            dr["fdept_id"] = this.strDeptID;
            dr["forder_by"] = "0";
            dr["fuse_flag"] = "1";

           
            if (strDeptID == "jyk")
            {
                dr["ftype"] = "检验";
            }
            else if (strDeptID == "kfz")
            {
                dr["ftype"] = "开发";
            }
            else
            {

                dr["ftype"] = "医生";
            }

            if (this.bllDept.Bllfp_id(strDeptID) == "jyk")
                dr["ftype"] = "检验";

            dtPerson.Rows.Add(dr);
        }
        private void butSave_Click(object sender, EventArgs e)
        {
            if (intEdit == 0)
            {
                SaveAdd();
            }
            else
            {
                SaveUpdate();
            }
        }

        private void butReturn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 将byte[]数组转换成Image
        /// </summary>
        /// <param name="btImage">byte[]</param>
        /// <returns>Image img</returns>
        public Image ByteToImg(byte[] btImage)
        {
            MemoryStream memStream = new MemoryStream();
            //Stream memStream = null;
            memStream.Write(btImage, 0, btImage.Length);
            memStream.Position = 0;
            memStream.Seek(0, SeekOrigin.Begin);
            //Bitmap bmp = new Bitmap(memStream, true);
            Image img;
            try
            {
                img = Image.FromStream(memStream, true);
                memStream.Close();
                //img = new Bitmap(memStream);

            }
            catch (Exception ex)
            {
                img = null;
            }
            finally
            {
                //memStream.Close();
            }
            return img;
        }

        /// <summary>
        /// 将一张图片转换为字节
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="imgFormat">保存图片的类型</param>
        /// <returns>byte[]</returns>
        public byte[] ImgToByte(Image img, System.Drawing.Imaging.ImageFormat imgFormat)
        {
            Bitmap bmp = new Bitmap(img);
            MemoryStream memStream = new MemoryStream();
            bmp.Save(memStream, imgFormat);
            memStream.Seek(0, SeekOrigin.Begin); //及时定位流的开始位置
            byte[] btImage = new byte[memStream.Length];
            memStream.Read(btImage, 0, btImage.Length);
            memStream.Close();
            return btImage;
        }

        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public static byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];

            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            return buff;
        }

        /// <summary>
        /// 将byte数组转换为文件并保存到指定地址
        /// </summary>
        /// <param name="buff">byte数组</param>
        /// <param name="savepath">保存地址</param>
        public static void Bytes2File(byte[] buff, string savepath)
        {
            if (System.IO.File.Exists(savepath))
            {
                System.IO.File.Delete(savepath);
            }

            FileStream fs = new FileStream(savepath, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(buff, 0, buff.Length);
            bw.Close();
            fs.Close();
        }

        string str_picpath = "";
        private void fpreson_imgPictureBox_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择图片";
            openFileDialog.CheckFileExists = true;
            openFileDialog.CheckPathExists = true;
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "图片文件(*.jpg,*.gif,*.bmp)|*.jpg|*.gif|*.bmp";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                str_picpath = openFileDialog.FileName;
                fpreson_imgPictureBox.Image = Image.FromFile(str_picpath); //PictureBox
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            str_picpath = "";
            dtPerson.Rows[0]["fpreson_img"] = null;
            //fpreson_imgPictureBox.Image = null;
            this.bll.BllCleareImg(this.strPersonID);
        }
    }
}